package aar.test.tessocr.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.AppointmentOrderNewActivity;
import aar.test.tessocr.DepositOrderMainActivity;
import aar.test.tessocr.EventMessage.EventMessage;
import aar.test.tessocr.MainActivity;
import aar.test.tessocr.OpenCabNewActivity;
import aar.test.tessocr.OrderListActivity;
import aar.test.tessocr.ScanLoginCabActivity;
import aar.test.tessocr.ScanLoginCabNewActivity;
import aar.test.tessocr.SiteDispatchActivity;
import aar.test.tessocr.SiteDispatchNewActivity;
import aar.test.tessocr.TimeOutListForCabinetActivity;
import aar.test.tessocr.TodayListActivity;
import aar.test.tessocr.adapter.OrderListAdapter;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CourierInfoModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.UnexporderListModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import butterknife.OnClick;
import clx.tessocr.ocreng.R;
import lib_zxing.activity.CodeUtils;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;
import static aar.test.tessocr.MainActivity.APP_KEY;
import static android.app.Activity.RESULT_OK;

/**
 * Created by fhapp on 2019/6/27.
 */

public class DepositFragment extends BaseFragment {
    private Button btn_cabinet_login;
    private TextView txt_cabinet_code;
    private TextView txt_overtime;
    private TextView txt_wait;
    private TextView txt_today;
    private List<UnexporderListModel> mList = new ArrayList<>();

    public static DepositFragment newInstance() {
        return new DepositFragment();
    }

    @Override
    protected void setUpContentView() {
        setContentView(R.layout.fragment_deposit);
    }

    @Override
    protected void setUpView(View view) {
        btn_cabinet_login = (Button) view.findViewById(R.id.login_button_cabinet);
        txt_cabinet_code = (TextView) view.findViewById(R.id.txt_cabinet_code);
        txt_today = (TextView) view.findViewById(R.id.txt_today);
        txt_wait = (TextView) view.findViewById(R.id.txt_wait);
        txt_overtime = (TextView) view.findViewById(R.id.txt_overtime);
        btn_cabinet_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(getActivity(), ScanLoginCabActivity.class);
                // 合合信息授权提供的APP_KEY
                intent1.putExtra("from", "isFromLogin");
                startActivityForResult(intent1, 100);
            }
        });

        txt_overtime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), OrderListActivity.class);
                intent.putExtra("type", "overtime");
                startActivity(intent);
            }
        });

        txt_wait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), OrderListActivity.class);
                intent.putExtra("type", "wait");
                startActivity(intent);
            }
        });

        txt_today.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), TodayListActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void setUpComponent() {
    }

    @Override
    protected void setUpData() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (null != data) {
                int mm = data.getIntExtra(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                if (mm == CodeUtils.RESULT_SUCCESS) {
                    btn_cabinet_login.setText(getString(R.string.login_cab_success_tip));
                    txt_cabinet_code.setText(BaseApplication.getIntance().getLoginCabModel().getCabinetcode());

                    if (requestCode == 200) {
                        getData(BaseApplication.getIntance().getLoginCabModel().getCabinetid());
                    }
                } else if (mm == CodeUtils.RESULT_FAILED) {
                    btn_cabinet_login.setText(getString(R.string.login_cab));
                }
            }
        }
    }

    @OnClick(R.id.deposit_quick)
    public void onViewClicked() {
        //快速投递，需先判断是否已经登录柜子，如果没有登录则登录，之后判断此柜子是否有逾期件要先处理再进行快速投递
        //如果登录了柜子，则直接判断此柜子是否有逾期件要先处理再进行快速投递
        if (!PrefUtils.getBoolean(getActivity(), "cabinetLoginFlag", false)) {
            //Toast.makeText(getActivity(),"没有柜子信息，请扫描登录",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), ScanLoginCabActivity.class);
            intent.putExtra("from", "isFromQuick");
            startActivityForResult(intent, 200);
        } else {
            getData(PrefUtils.getString(getActivity(), "cabinetId", ""));
        }


        /*if (!txt_overtime.getText().toString().trim().equals("逾期件\n0")) {
            Toast.makeText(getActivity(),"请先处理逾期件!",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), OrderListActivity.class);
            intent.putExtra("type", "overtime");
            startActivity(intent);
        } else {

        }*/
    }

    private void getData(String cabinetId) {
        if (TextUtils.isEmpty(PrefUtils.getString(getActivity(), "userId", ""))) {
            Toast.makeText(getActivity(), "登录信息为空", Toast.LENGTH_SHORT).show();
            return;

        }

        final Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(getActivity(), "userId", ""));
        map.put("keyword", "");
        map.put("page", "1");
        map.put("size", ConstantPara.PAGESIZE_MAX);
        map.put("cabinetId", cabinetId);


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<UnexporderListModel>>>post(Urls.URL_TIMEOUT_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<UnexporderListModel>>>(getActivity()) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        mList.clear();
                        mList.addAll(response.body().data);
                        if (mList.size() == 0) {
                            Intent intent = new Intent(getActivity(), SiteDispatchNewActivity.class);
                            // 合合信息授权提供的APP_KEY
                            intent.putExtra(MainActivity.EXTRA_KEY_APP_KEY, APP_KEY);
                            startActivity(intent);
                        } else {
                            Toast.makeText(getActivity(),"请先处理当前柜子的逾期件!",Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("unexporderListModel", (Serializable) mList);
                            intent.putExtras(bundle);
                            intent.setClass(getActivity(),TimeOutListForCabinetActivity.class);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        Intent intent = new Intent(getActivity(), SiteDispatchNewActivity.class);
                        // 合合信息授权提供的APP_KEY
                        intent.putExtra(MainActivity.EXTRA_KEY_APP_KEY, APP_KEY);
                        startActivity(intent);
                    }
                });
    }

    @OnClick(R.id.deposit_order)
    public void onViewClicked2() {
        /*if (!txt_overtime.getText().toString().trim().equals("逾期件\n0")) {
            Toast.makeText(getActivity(),"请先处理逾期件!",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), OrderListActivity.class);
            intent.putExtra("type", "overtime");
            startActivity(intent);
        } else {
            *//*if (!PrefUtils.getBoolean(getActivity(), "cabinetLoginFlag", false)) {
                //Toast.makeText(getActivity(),"没有柜子信息，请扫描登录",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), ScanLoginCabActivity.class);
                intent.putExtra("from", "isFromAppointment");
                startActivity(intent);
            } else {
                startActivity(new Intent(getActivity(), DepositOrderMainActivity.class));
            }*//*


        }*/

        startActivity(new Intent(getActivity(), DepositOrderMainActivity.class));
    }

   /* @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShutDown(EventMessage eventMsg) {
        String msg = eventMsg.getMessage();
        if (msg.equals("LoginCabSuccess")) {
            btn_cabinet_login.setText(getString(R.string.login_cab_success_tip));
            txt_cabinet_code.setText(BaseApplication.getIntance().getLoginCabModel().getCabinetcode());
        }
    }*/

    @Override
    public void onResume() {
        super.onResume();
        Map<String, Object> map = new HashMap<>();
        //map.put("adminid", BaseApplication.getIntance().getLoginBean().getId());
        map.put("adminid", PrefUtils.getString(getActivity(), "userId", ""));

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<CourierInfoModel>>post(Urls.URL_CHARGEINFO)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<CourierInfoModel>>(getActivity()) {
                    @Override
                    public void onSuccess(Response<LzyResponse<CourierInfoModel>> response) {
                        if (null != response.body().data) {
                            CourierInfoModel courierInfoModel = response.body().data;
                            txt_overtime.setText("逾期件\n" + courierInfoModel.getOverdue());
                            txt_today.setText("今日投递\n" + courierInfoModel.getToday());
                            txt_wait.setText("未取件\n" + courierInfoModel.getWaiting());
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<CourierInfoModel>> response) {
                    }
                });

        if (PrefUtils.getBoolean(getActivity(), "cabinetLoginFlag", false)) {
            btn_cabinet_login.setText(getString(R.string.login_cab_success_tip));
            txt_cabinet_code.setText(PrefUtils.getString(getActivity(), "cabinetCode", "无"));
        }
    }
}
